#!/bin/bash

# logrun - Wrapper script to run commands with automatic logging using script
# Usage: logrun <command> [args...]
# Example: logrun gsm test-remote --solver=gcr --gpu=hip --debug

set -e

# Check if any arguments were provided
if [ $# -eq 0 ]; then
    echo "Usage: logrun <command> [args...]"
    echo "Example: logrun gsm test-remote --solver=gcr --gpu=hip --debug"
    exit 1
fi

# Extract the base command and subcommand for log file naming
BASE_CMD="$1"
if [ $# -ge 2 ]; then
    SUB_CMD="$2"
    LOG_NAME="${BASE_CMD}_${SUB_CMD}"
else
    LOG_NAME="$BASE_CMD"
fi

# Generate timestamp
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

# Create log filename
LOG_FILE="${LOG_NAME}-${TIMESTAMP}.log"

# Create logs directory if it doesn't exist
mkdir -p logs

# Full path to log file
FULL_LOG_PATH="logs/${LOG_FILE}"

echo "🚀 Starting logged session: $*"
echo "📝 Log file: $FULL_LOG_PATH"
echo "⏰ Started at: $(date)"
echo ""

# Check if script command is available
if ! command -v script >/dev/null 2>&1; then
    echo "❌ Error: 'script' command not found. Please install util-linux package."
    exit 1
fi

# Run the command with script logging
# Use script with -c option to run the command directly
script -c "$*" "$FULL_LOG_PATH"

EXIT_CODE=$?

echo ""
echo "⏰ Finished at: $(date)"
if [ $EXIT_CODE -eq 0 ]; then
    echo "✅ Command completed successfully"
else
    echo "❌ Command failed with exit code: $EXIT_CODE"
fi
echo "📝 Full log saved to: $FULL_LOG_PATH"

exit $EXIT_CODE